import os
import json
import mysql.connector

# 获取脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))

# 构建文件路径
file_path = os.path.join(script_dir, 'books', 'detail_400000.json')

# 读取 JSON 文件
with open(file_path, 'r', encoding='utf-8') as file:
    data = json.load(file)

# 打印解析后的数据
print(data)

# 连接到 MySQL 数据库
conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='root',
    database='booksys'
)
cursor = conn.cursor()

print("数据库连接成功")

# 创建表（如果表不存在）
cursor.execute('''
CREATE TABLE IF NOT EXISTS book (
    name VARCHAR(55),
    image_url VARCHAR(55),
    author VARCHAR(55),
    dscript VARCHAR(1000)
)
''')

# 插入数据
try:
    for book in data:
        cursor.execute('''
        INSERT INTO book (name, image_url, author, dscript, rating)
        VALUES (%s, %s, %s, %s, %s)
        ''', (book['title'], book['image_url'], book['author'], book['description'], book['rating']))
    print("数据插入成功")
except mysql.connector.Error as err:
    print(f"数据插入失败: {err}")
    conn.rollback()
    conn.close()
    exit(1)


# 提交事务
conn.commit()

# 关闭连接
conn.close()